<?php
class Links extends BlockInstance {
	public $CI;
	
	public function __construct()
	{
		$this->CI =& get_instance();
	}
	
	public function __call($m, $a)
	{
		global $BBX;
		$bricabox = $BBX['bricabox'];
		if (preg_match('/[a-z]+_([a-z]+)/', $m, $matches))
		{
			if ($matches[1] == 'content')
			{
				$content = $a[1];
				$data 	 = array(
					'block_instance' => $a[0],
					'links'			 => $this->_get_links($a[0]['data']->id, $content->id),
					'bricabox'		 => $bricabox,
					'content_id'	 => $content->id
				);
				$this->CI->load->view('blocks/links/content', $data);
			}
			elseif ($matches[1] == 'homepage')
			{
				$data = array(
					'block_instance' => $a[0],
					'links'			 => $this->_get_links($a[0]['data']->id, -$bricabox->id),
					'bricabox'		 => $bricabox,
					'content_id'	 => $this->_calc_content_id($a[0]['data']->id, -$bricabox->id)
				);
				$this->CI->load->view('blocks/links/homepage', $data);
			}
		}
	}
	
	private function _get_links($instance_id, $content_id)
	{
		$id	   = $this->_calc_content_id($instance_id, $content_id);
		$query = $this->CI->db->query("SELECT * FROM link_list
		WHERE content_id = ?
		ORDER BY created_at DESC", $id);
		return $query->num_rows() ? $query : false;
	}
	
	private function _calc_content_id($instance_id, $content_id)
	{
		return ($content_id > 0) ? $content_id : (intval($instance_id . (-1 * $content_id)) * -1);
	}
}
?>